package org.zebra.tenant.mybatis;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import lombok.AllArgsConstructor;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import net.sf.jsqlparser.expression.NullValue;
import net.sf.jsqlparser.expression.StringValue;
import org.zebra.tenant.TenantHelper;
import org.zebra.tenant.config.TenantProperties;

import java.io.Serializable;
import java.util.List;

/**
 * @author zhanghongbin
 */
@AllArgsConstructor
public class TenantLineHandlerImpl implements TenantLineHandler {

    private TenantProperties tenantProperties;

    @Override
    public Expression getTenantId() {
        Serializable tenantIdSerializable = TenantHelper.getTenantId();
        if (tenantIdSerializable == null) {
            return new NullValue();
        }
        if (tenantProperties.getIdType().equals("String")) {
            String tenantId = tenantIdSerializable.toString();
            return new StringValue(tenantId);
        } else {
            long tenantId = Long.parseLong(tenantIdSerializable.toString());
            return new LongValue(tenantId);
        }
    }

    @Override
    public boolean ignoreTable(String tableName) {
        List<String> excludes = tenantProperties.getExcludes();
        return excludes.contains(tableName);
    }
}
